package com.hmo.appshop.mamager.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmo.appshop.mamager.bean.User;
import com.hmo.appshop.mamager.dto.commom.JwtTokenUtil;
import com.hmo.appshop.mamager.dto.user.UserDetails;
import com.hmo.appshop.mamager.dto.user.UserDto;
import com.hmo.appshop.mamager.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service("userService")
public class UserService {

    @Autowired
    PasswordEncoder passwordEncoder;
    @Autowired
    JwtTokenUtil jwtTokenUtil;
    @Resource
    private UserMapper userMapper;

    public int selectAllNumber(){
        Integer integer = userMapper.selectCount(null);
        return integer;
    }

    public User register(User user){
        Integer count = userMapper.selectCount(new QueryWrapper<User>().eq("username", user.getUsername()));
        if (count==0){//重名
            int insert = userMapper.insert(user);
            if (insert==1){
                return user;
            }
        }
        return null;
    }

    //请求拦截认证需要
    public UserDetails loadUserByUsername(String username){
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        if (user==null)
            throw new UsernameNotFoundException("用户名未找到");
        return new UserDetails(user);
    }

    public String login(UserDto u) {
        String token=null;
        UserDetails userDetails = loadUserByUsername(u.getUsername());
        if (userDetails.getPassword().equals(u.getPassword())){//密码验证
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            token = jwtTokenUtil.generateToken(userDetails);
        }
        return token;
    }


}
